/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-11-01 14:23:34
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2023-02-17 10:49:42
 */
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import {
  showMsg
} from '../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../utils/validate.js'
import {
  reqSpaceAdd,
  reqSpaceBatchAdd
} from '../../../../request/api'
Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    parkId: '', //园区id
    pid: '', //父id
    form: {
      name: '', //单个添加楼层名称
      isDefence: true,
      // metaCode: 3, //空间类型 
      buildingType: 3,
      childrenName: [], //批量新增下级空间名称
    },
    imageList: [],
    imageCount: 6, //照片数量限制6张
    radio: "1", //单个添加/批量添加
    batchNameList: [{
      id: 0,
      start: '',
      end: ''
    }, ], //批量添加
    disabledBtn: false,
  },
  onLoad(e) {
    this.getParkId(e)
  },
  // 获取园区id
  getParkId(e) {
    let params = JSON.parse(e.params)
    this.setData({
      parkId: params.parkId,
      pid: params.pid,
      orgId: params.orgId,
    })
  },
  // 点击布撤防
  changeDefence(e) {
    let tip = e.detail ? '此操作将开启该安装点所有设备布防设置，是否继续？' : '此操作将关闭该安装点所有设备布防设置，是否继续？'
    Dialog.confirm({
        title: '温馨提示',
        message: tip,
      })
      .then(async () => {
        this.setData({
          "form.isDefence": e.detail
        })
      })
      .catch(() => {});
  },

  // 选择单个添加/批量添加
  radioChange(e) {
    this.setData({
      radio: e.detail
    })
  },
  // 单个添加获取名称
  nameChange(e) {
    this.data.form.name = validateEmoji(e.detail.value.replace(/\s+/g, ''))
    this.setData({
      "form.name": this.data.form.name
    })
  },
  // 单个添加清除
  clearname() {
    this.setData({
      'form.name': ''
    })
  },
  // 点击新增一条楼层段
  clickAddFloor() {
    let {
      batchNameList
    } = this.data
    if (batchNameList.length > 1) return Toast('最多只允许添加两个安装点信息');
    let id = batchNameList.length === 0 ? 0 : batchNameList[batchNameList.length - 1].id + 1
    batchNameList.push({
      id,
      start: '',
      end: ''
    })
    this.setData({
      batchNameList
    })
  },
  // 获取开始层数
  floorStartChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    let {
      batchNameList
    } = this.data
    // 正则表达式
    let value2 = value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value2 = value2.replace(/\-{2,}/g, "-"); // -只能保留一个
    value2 = value2.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value2 = value2.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value2 = value2.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value2 > 49) {
      value2 = 49
    }
    if (value2 < -3) {
      value2 = -3
    }
    if (value2 == '0') {
      value2 = 1
    }
    batchNameList.forEach(item => {
      if (item.id === id) {
        item.start = value2
      }
    })
    this.setData({
      batchNameList
    })
  },

  // 获取结束层数
  floorEndeChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    let {
      batchNameList
    } = this.data
    // 正则表达式
    let value2 = value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value2 = value2.replace(/\-{2,}/g, "-"); // -只能保留一个
    value2 = value2.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value2 = value2.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value2 = value2.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value2 > 50) {
      value2 = 50
    }
    if (value2 < -3) {
      value2 = -3
    }
    if (value2 == '0') {
      value2 = 1
    }
    batchNameList.forEach(item => {
      if (item.id === id) {
        item.end = value2
      }
    })
    this.setData({
      batchNameList
    })
  },
  // 删除一条
  deleteBatchName(e) {
    let {
      id
    } = e.target.dataset
    let {
      batchNameList
    } = this.data
    batchNameList.splice(id, 1)
    batchNameList.forEach((item, index) => {
      item.id = index
    })
    this.setData({
      batchNameList
    })
  },

  // ------------照片开始
  addImage() {
    let {
      imageList
    } = this.data
    if (imageList.length >= 6) return showMsg("安装照片最多添加6张")
    this.uploadFileFun()
  },
  uploadFileFun(updateItem) {
    let that = this
    wx.chooseImage({
      count: this.data.imageCount,
      success(res) {
        console.log(res);

        var PicNums = res.tempFiles.length;
        for (var inta = 0; inta < PicNums; inta++) {
          var path = res.tempFiles[inta].path;
          var formatImage = path.split(".")[(path.split(".")).length - 1];
          console.log("图片格式" + formatImage)
          // 判断格式
          if (formatImage != "png" && formatImage != "jpg") {
            showMsg("只能上传.png、.jpg格式")
          }
          // 判断大小
          let size = res.tempFiles.every(item => { //限制上传图片大小为2M,所有图片少于2M才能上传   return item.size <= 2000000
            return item.size <= 20000000 //return item.size <= 2000000
          })
          console.log(size);
          if (!size) {
            showMsg("图片大小不能超过20MB!")
            return;
          }
        }



        const tempFilePaths = res.tempFilePaths
        if (tempFilePaths.length > 6) return showMsg("安装照片最多添加6张")
        tempFilePaths.forEach(item => {
          wx.uploadFile({
            url: app.globalData.reqUrl + 'file/upload',
            filePath: item,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            formData: {
              "token": app.globalData.token,
              "file": item,
            },
            success: function (res) {
              let data = JSON.parse(res.data)
              console.log(data);
              if (data.code == 20000) {
                that.updateImageList(data.data.url, updateItem)
                return showMsg("上传成功")
              } else {
                return showMsg("上传失败")
              }
            },
            fail: function (e) {
              return showMsg("上传失败")
            }
          })
        })
      }
    })
  },
  // 上传成功后更新照片列表
  updateImageList(url, updateItem) {
    let {
      imageList
    } = this.data
    if (updateItem && updateItem.src) {
      // 更新图片
      imageList.forEach(citem => {
        if (citem.id === updateItem.id) {
          citem.src = url
        }
      })
      imageList.forEach((citem, index) => {
        citem.id = index
      })
      this.setData({
        imageList,
        imageCount: 6 - imageList.length
      })

    } else {
      // 添加图片 
      console.log(imageList.length);
      let id = 0
      if (imageList.length > 0) {
        id = imageList.length
      }
      imageList.push({
        id,
        src: url
      })
      this.setData({
        imageList,
        imageCount: 6 - imageList.length
      })
    }

    console.log(this.data.imageList);
  },

  // 点击照片  发生的操作：预览、编辑、删除
  iamgeClick(e) {
    let {
      item
    } = e.currentTarget.dataset
    let that = this
    wx.showActionSheet({
      itemList: ['预览图片', '更新图片'],
      success(res) {
        let {
          tapIndex
        } = res
        if (tapIndex === 0) {
          that.previewImageFun(item)
        } else if (tapIndex === 1) {
          that.updateImageFun(item)
        } else {
          that.delImageFUn(item)
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  // 1、预览图片
  previewImageFun(item) {
    let {
      imageList
    } = this.data
    let urls = imageList.map(item => {
      return item.src
    })
    wx.previewImage({
      current: item.src, // 当前显示图片的http链接
      urls, // 需要预览的图片http链接列表
    })
  },
  // 2、更新图片
  updateImageFun(item) {
    this.uploadFileFun(item)
  },
  // 3、删除图片
  delImageFUn(e) {
    // console.log(item);
    let {
      item
    } = e.currentTarget.dataset
    let {
      imageList
    } = this.data
    imageList.forEach(citem => {
      if (citem.id === item.id) {
        imageList.splice(item.id, 1)
      }
    })
    imageList.forEach((citem, index) => {
      citem.id = index
    })
    this.setData({
      imageList,
      imageCount: 6 - imageList.length
    })
  },
  // ------------照片结束

  /**
   * @name: 确认新增楼层
   * @msg: *orgId:组织id  *parkId：园区id *name：名称    *isDefence：布撤防  *buildingType：空间类型  childrenName批量新增下级空间名称
   * @return {*}
   */

  confirm() {
    if (this.data.disabledBtn) return
    let {
      radio,
      batchNameList,
      form,
      imageList
    } = this.data
    if (imageList.length > 6) return showMsg("安装照片最多添加6张")
    let picList = imageList.map(item => {
      return item.src
    })
    if (radio == 2) {
      let params = {
        pid: this.data.pid,
        nameList: []
      }
      let arr = []
      let flag = false
      let flag1 = false
      let index = 0
      let index1 = 0
      try {
        batchNameList.forEach(item => {
          if (item.start > item.end) {
            index = item.id + 1
            flag = true
            throw new console.log(`第${index}项错误`);
          }
          if (item.start === '') {
            flag1 = true
            index1 = item.id + 1
            throw new console.log(`第${index1}项错误`);
          }
          for (let i = item.start; i <= item.end; i++) {
            if (i != 0) {
              arr.push(`${i}`)
            }
          }
        })
      } catch (e) {
        console.log(e);
      }
      if (flag) return showMsg(`第${index}项结束安装点小于开始安装点，请检查！`)
      if (flag1) return showMsg(`第${index1}项开始安装点数未填写，请检查！`)
      params.nameList = Array.from(new Set(arr));
      params.nameList.forEach((item, index) => {
        if (!item) {
          params.nameList.splice(index, 1)
        }
      })
      if (!params.nameList[0]) return showMsg("请输入")
      if (params.nameList.length > 50) return showMsg("一次最多添加50个安装点")
      this.reqSpaceBatchAddFun(params)
    } else {
      if (!(form.name)) return showMsg("请输入名称")
      if (!validateSpecial(form.name)) return
      let params = {
        orgId: this.data.orgId,
        pid: this.data.pid,
        name: form.name,
        lng: '',
        lat: '',
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        area: '',
        areaCode: '',
        street: '',
        streetCode: '',
        address: '',
        isDefence: form.isDefence ? 1 : 0,
        // metaCode: form.metaCode,
        buildingType: form.buildingType,
        childrenName: [],
        picList,
        village: ''
      }
      this.reqSpaceAddFun(params)
    }

  },
  // 单个添加
  async reqSpaceAddFun(params) {
    const res = await reqSpaceAdd(params)
    if (res.code != 20000) return showMsg(res.message)
    showMsg("新增成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000)
  },

  // 批量添加
  async reqSpaceBatchAddFun(params) {
    const res = await reqSpaceBatchAdd(params)
    if (res.code != 20000) return showMsg(res.message)
    showMsg("新增成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000)
  },

})